// pages/main/audio/audio.js

const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()
 
Page({
 
  data: {
    list: [{ "name": "播放录音" }, { "name": "停止录音" }, { "name": "点击录音" }],
    recordSetInter: null,
    src: null,
  },
  /**  
   * 生命周期函数--监听页面加载  
   */
  onLoad: function (options) {
    let that = this;
    console.log(recorderManager);
    recorderManager.onStop((res) => {
      console.log('停止录音', res.tempFilePath);
      const { tempFilePath } = res;
      that.setData({
        src: tempFilePath 
      });
    });
  },
  // 获取当前选项
  btn_sub:function(res){
    var name = res.currentTarget.dataset.name;
    var that=this;
    console.log(res.currentTarget.dataset.name);
      if (name =="停止录音"){
        that.stop();
      } else if (name =="播放录音"){
        that.play();
      } else if (name =="点击录音"){
        that.start();
      }
  },
  //开始录音的时候
  start: function() {
    const options = {
      duration: 10000,
      sampleRate: 44100,
      numberOfChannels: 1,
      encodeBitRate: 192000,
      format: 'mp3',
      frameSize: 50
    }
    
    recorderManager.start(options)
  },
  start1: function () {
    let that = this;
    
    if (true) {

      wx.showToast({
        title: '开始录音',
        duration: 3
      })
      wx.startRecord({
        success: function (res) {
          console.log('获取语音权限');
          
        },
        complete : function (){
          if(that.recordSetInter) clearInterval(that.recordSetInter);
          wx.hideToast();
        }
      })

      // console.log('语音权限 ', hasRecord);
      that.recordSetInter = setInterval(function (){

        wx.stopRecord();
      },500);
      // hasRecord = true;
    }else{
      wx.showToast({
        title: '已经有麦克风权限',
      })
    }

    const options = {
      duration: 10000,//指定录音的时长，单位 ms
      sampleRate: 16000,//采样率
      numberOfChannels: 1,//录音通道数
      encodeBitRate: 96000,//编码码率
      format: 'mp3',//音频格式，有效值 aac/mp3
      frameSize: 50,//指定帧大小，单位 KB
    }
    //开始录音
    recorderManager.start(options);
    recorderManager.onStart(() => {
      console.log('recorder start')
    });
    //错误回调
    recorderManager.onError((res) => {
      console.log(res);
    })
  },
 
  //停止录音
  stop: function () {
    recorderManager.stop();
  },
 
 
  //播放声音
  play() {
    let that = this;
      innerAudioContext.onError((error) => {
      // 播放音频失败的回调
      console.log('play eror', error);
      })
      innerAudioContext.src = that.data.src;  // 这里可以是录音的临时路径
      innerAudioContext.play();
  },
  play1: function () {
    innerAudioContext.autoplay = true
    innerAudioContext.src = this.tempFilePath,
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    innerAudioContext.onError((res) => {
      console.log(res.errMsg)
      console.log(res.errCode)
    })
  },
 
 
});
